﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using SuperiorCommon;
using SuperiorModel;
using SuperiorShopBussinessService;
using System.Text;
using Newtonsoft.Json.Linq;
using WxPayAPIMobileShopCode.Common.Helpers;

namespace H5.SuperiorShop.Controllers.Service
{
    [JsonException]
    public class ManagerAccountController : BaseController
    {
        private readonly IManagerAccountService _IManagerAccountService;

        public ManagerAccountController(IManagerAccountService IManagerAccountService)
        {
            _IManagerAccountService = IManagerAccountService;
        }
        protected override void Dispose(bool disposin)
        {
            this._IManagerAccountService.Dispose();
            base.Dispose(disposin);
        }
        // GET: ManagerAccount
        /// <summary>
        /// 推广人页面
        /// </summary>
        /// <returns></returns>
        [CheckMangerAccountLoginFitler]
        public ActionResult Index()
        {
            var user = Session[SessionKey.ServiceManagerAccountKey] as ManagerAccountModel;
            var _managerAccountId = SecretClass.DecryptQueryString(user.Id).ToInt();
            //获取总单数
            var totalCount = _IManagerAccountService.GetProceedsCount(_managerAccountId);
            ViewBag.Total = totalCount;
            ViewBag.Amount = user.Amount;
            ViewBag.ManagerId = SecretClass.DecryptQueryString(user.Id);
            //获取提现记录第一页数据
            var cashList = GetServiceCashOutLogItemList(_managerAccountId,0,10);
            ViewBag.CashList = cashList;
            return View(user);
        }

        private List<ServiceCashOutLogItem> GetServiceCashOutLogItemList(int managerAccountId, int pageIndex, int pageSize)
        {
            return _IManagerAccountService.SearchServiceCashOutLogItemList(managerAccountId, pageIndex, pageSize);
        }
        /// <summary>
        /// 分页加载提现记录
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [AjaxOnly]
        [CheckMangerAccountLoginFitler]
        public JsonResult SearchCashOutList(int pageIndex, int pageSize)
        {
            var user = Session[SessionKey.ServiceManagerAccountKey] as ManagerAccountModel;
            var _managerAccountId = SecretClass.DecryptQueryString(user.Id).ToInt();
            var model = GetServiceCashOutLogItemList(_managerAccountId, pageIndex, pageSize);
            return Success(model);
        }
        /// <summary>
        /// 推广人收益列表
        /// </summary>
        /// <returns></returns>
        /// 
        [CheckMangerAccountLoginFitler]
        public ActionResult ProceedsList()
        {
            var user = Session[SessionKey.ServiceManagerAccountKey] as ManagerAccountModel;
            var _managerAccountId = SecretClass.DecryptQueryString(user.Id).ToInt();
            var model = GetServiceProceedsItemList(_managerAccountId, 0, 10);
            
            return View(model);
        }
        /// <summary>
        /// 分页加载收益数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// 
        [AjaxOnly]
        [CheckMangerAccountLoginFitler]
        public JsonResult SearchProceedsList(int pageIndex, int pageSize)
        {
            var user = Session[SessionKey.ServiceManagerAccountKey] as ManagerAccountModel;
            var _managerAccountId = SecretClass.DecryptQueryString(user.Id).ToInt();
            var model = GetServiceProceedsItemList(_managerAccountId, pageIndex, pageSize);
            return Success(model);
        }

        private List<ServiceProceedsItem> GetServiceProceedsItemList(int managerAccountId, int pageIndex, int pageSize)
        {
            return _IManagerAccountService.SearchServiceProceedsItemList(managerAccountId,pageIndex,pageSize);
        }

        /// <summary>
        /// 提交提现
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [CheckMangerAccountLoginFitler]
        [AjaxOnly]
        [HttpPost]
        public JsonResult SubmitAmount(Shop_SubmitAmountParms model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            if (model.Amount == 0)
                return Error("提现金额必须大于0");
            var user = Session[SessionKey.ServiceManagerAccountKey] as ManagerAccountModel;
           
            //系统下单
            string msg = "";
            var orderno = ToolManager.CreateNo();
            var _managerAccountId = SecretClass.DecryptQueryString(user.Id).ToInt();
            var requestModel = _IManagerAccountService.CreateCashOutOrder(_managerAccountId, model.Amount, orderno, out msg);
            if (msg != "")
                return Error(msg);

            //var ret = RequestWxCashOut(orderno,requestModel.OpenId,model.Amount);
            //var status = ret ? 1 : 2;
            ////异步更新此订单状态
            //Task.Factory.StartNew(() =>
            //{
            //    _IManagerAccountService.UpdateCashCoutOder(orderno,status);
            //});
            //更新用户session
            user.Amount =Convert.ToDecimal(requestModel.ExpressAmount);
            SessionManager.SetSession(SessionKey.ServiceManagerAccountKey, user,"",15);
            return Success(requestModel.ExpressAmount);
        }

        private bool RequestWxCashOut(string orderno, string openid, decimal amount)
        {
            var res = true;
            //微信企业付款
            var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
            WxPayData data = new WxPayData();
            data.SetValue("mch_appid", ConfigSettings.Instance.APPID);//公众账号ID
            data.SetValue("mchid", ConfigSettings.Instance.Merchant_Id);//商户号
            data.SetValue("nonce_str", ToolManager.GenerateNonceStr());//随机字符串
            data.SetValue("partner_trade_no", orderno);
            data.SetValue("openid", openid);
            data.SetValue("check_name", "NO_CHECK");
            data.SetValue("amount", (int)Math.Round(amount * 100));//总金额 单位分
            data.SetValue("desc", "超奇科技向用户" + openid + "付款");
            data.SetValue("spbill_create_ip", Net.Ip);//终端ip
            data.SetValue("sign", data.MakeSign(ConfigSettings.Instance.PaySecret));
            string xml = data.ToXml();
            string response = WeiXinHelper.Post(xml, url, true, 10);
            LogManger.Instance.WriteLog("企业微信付款请求返回:" + response);
            WxPayData result = new WxPayData();
            result.FromXml(response);
            //签名验证
            // 错误时没有签名
            if (result.IsSet("return_code") && result.GetValue("return_code").ToString() == "SUCCESS")
            {
                //请求成功
                if (result.GetValue("result_code").ToString() == "SUCCESS")
                {
                    //说明转账一定成功了
                    res = true;
                }
                else
                {
                    res = false;//不一定是失败，系统暂时定为失败，后台工作人员人工操作时，先查询微信商户系统确认，再手工微信转账
                }

            }
            else
            {
                if (result.IsSet("return_msg") && result.GetValue("return_msg").ToString() != "")
                {
                    LogManger.Instance.WriteLog("订单号：" + orderno + ";企业微信付款失败：" + result.GetValue("return_msg").ToString());
                    res = false;
                }
                else
                {
                    res = false;
                }
            }
            return res;
        }

        public ActionResult Login()
        {
            string code = Request["code"];
            var appid = ConfigSettings.Instance.APPID;
            var secret = ConfigSettings.Instance.APP_Secret;
            if (!string.IsNullOrEmpty(code))
            {
                //通过code换取网页授权access_token
                string tokens = WeiXinHelper.GetToken(appid, secret, code);
                try
                {
                    JObject jo = JObject.Parse(tokens);
                    string openid = jo["openid"].ToString();
                    string access_token = jo["access_token"].ToString();

                    if (!string.IsNullOrEmpty(openid) && !string.IsNullOrEmpty(access_token))
                    {
                        LogManger.Instance.WriteLog("openid:" + openid + "-------token:" + access_token);
                        //读取用户最新信息
                        string jsonstr = WeiXinHelper.GetUserInfo(access_token, openid);
                        LogManger.Instance.WriteLog("获取推广人USERiNFO" + jsonstr);
                        Newtonsoft.Json.Linq.JObject joUser = Newtonsoft.Json.Linq.JObject.Parse(jsonstr);

                        var headImgUrl = joUser["headimgurl"].ToString();
                        var nickName = joUser["nickname"].ToString();

                        //更新或者登录
                        var user =  _IManagerAccountService.Wx_Login(openid,headImgUrl,nickName);
                        SessionManager.SetSession(SessionKey.ServiceManagerAccountKey,user,"",15);
                        Response.Redirect("/ManagerAccount/Index", false);
                        return new EmptyResult();
                    }
                    else
                    {
                        Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("获取微信信息失败", Encoding.UTF8));
                        return new EmptyResult();
                    }
                }
                catch (Exception ex)
                {
                    LogManger.Instance.WriteLog("获取推广人access_token异常:" + ex.ToString());
                    Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("获取access_token异常", Encoding.UTF8));
                    return new EmptyResult();
                }

            }
            else
            {
                //发起请求
                var redirect = ConfigSettings.Instance.WebHost + "ManagerAccount/Login";
                string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + HttpUtility.UrlEncode(redirect, Encoding.UTF8) + "&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect";
                Response.Redirect(url);

                //测试
                //var user = _IManagerAccountService.GetModel(1);
                //SessionManager.SetSession(SessionKey.ServiceManagerAccountKey, user,15);
                //Response.Redirect("/ManagerAccount/Index", false);


                return new EmptyResult();
            }
        }

    }
}